//
//  HEHealthCheckChartController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/21.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthCheckChartController2.h"
#import "HEDataManageModel.h"
#import "HEHealthCheckRecodCell.h"
#import "BRStringPickerView.h"

@import Charts;
 
@import SwiftCus;

@interface HEHealthCheckChartController2 () < UITableViewDelegate, UITableViewDataSource, ChartViewDelegate>

@property (nonatomic, strong) LineChartView *chartView;
@property (nonatomic, strong) NSMutableArray *xAixTitles;
@property (nonatomic, strong) NSMutableArray *yValues;
@property (nonatomic, strong) UIView *chartWarp;

@property (nonatomic, strong) NSMutableArray <HEDataManageModel *> *dataSourceArr;
@property (nonatomic, strong) NSArray *lineColors;

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) UIButton *bottomView;

@end

@implementation HEHealthCheckChartController2

- (NSMutableArray<HEDataManageModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.zx_navBar.hidden = YES;

    [self initUI];
    
    HEEmptyDataModel *empt = [HEEmptyDataModel new];
    empt.tipsImageName = @"index_no_data";
    empt.tipsTitle = [NSString stringWithFormat:@"还没有记录过%@", _model.check_name];;
    empt.tipsDetailTitle = @"记录数据后在这里会看到变化趋势哦";
    [self customEmptyModel:empt];
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    
    [self initChart];
    
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBindUser:) name:KNotificationSelectBindUser object:nil];
}

- (void)changeBindUser:(NSNotification *)notif {
    _selectUser = (HEBindUserModel *)notif.object;
    [_tableView.mj_header beginRefreshing];
}

- (void)loadData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_selectUser.id forKey:@"usid"];
    [dict setValue:_model.check_code forKey:@"check_code"];

    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KHealthBasicinfo parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
       
        [self.dataSourceArr removeAllObjects];

        [self.dataSourceArr addObjectsFromArray:[HEDataManageModel mj_objectArrayWithKeyValuesArray:response.data]];
        self.xAixTitles = @[].mutableCopy;
        self.yValues = @[].mutableCopy;
        
        NSMutableArray *yValu1 = @[].mutableCopy;
        NSMutableArray *yValu2 = @[].mutableCopy;

        NSArray *datas = [[self.dataSourceArr reverseObjectEnumerator] allObjects];
        for (int i = 0; i < datas.count; i++) {
            HEDataManageModel *model = datas[i];
            model.check_unit = self.model.check_unit;
            
            NSString *xTitle = [NSDate timestampToDate:model.create_date formaterMode:NSDateFormaterModeMD];
            [self.xAixTitles addObject: xTitle];
            
            if ([self.model.check_name isEqualToString:@"血压"]) {
                NSArray *vals = [model.check_value componentsSeparatedByString:@"/"];
                [yValu1 addObject:vals.firstObject];
                [yValu2 addObject:vals.lastObject];
            }else {
                [yValu1 addObject:[NSString stringWithFormat:@"%@", model.check_value]];
            }
        }
        if ([self.model.check_name isEqualToString:@"血压"]) {
            [self.yValues addObject: yValu1];
            [self.yValues addObject: yValu2];
        }else {
            [self.yValues addObject: yValu1];
        }

        [self setupXAixTitle];
        [self setData];
        
        if (self.dataSourceArr.count == 0) {
            self.tableView.tableHeaderView = [UIView new];
            [self showEmpty];
            
            if (![self.model.check_name isEqualToString:@"BMI"]) {
                [self.view addSubview:self.bottomView];
            }
        }else {
            
            if (![self.model.check_name isEqualToString:@"BMI"]) {
                [self.view addSubview:self.bottomView];
                self.tableView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight - ZXNavBarHeight - 47 - 49);
            }
            self.tableView.tableHeaderView = self.chartWarp;
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];

     } failure:^(NSError * _Nonnull error) {
         [self.tableView.mj_header endRefreshing];
    }];
}


- (void)initChart {
    
    _chartWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 215)];
    
    _yValues = @[].mutableCopy;
    _xAixTitles = @[].mutableCopy;
    _lineColors = @[CNavBgColor, KHexColor(@"FFA900")];
    
    _chartView = [[LineChartView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 200)];
    _chartView.backgroundColor = KWhiteColor;
    [_chartWarp addSubview: _chartView];

//    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).offset(ZXNavBarHeight + 15);
//        make.left.equalTo(self.view).offset(0);
//        make.right.equalTo(self.view).offset(-0);
//        make.height.offset(200);
//    }];

    _chartView.userInteractionEnabled = YES;

    _chartView.delegate = self;
    _chartView.minOffset = 20; // 内边距

    _chartView.chartDescription.enabled = NO;
    _chartView.dragEnabled = YES;
    [_chartView setScaleEnabled:YES];
    _chartView.pinchZoomEnabled = YES;
    _chartView.drawGridBackgroundEnabled = NO;
    
    
    if ([_model.check_name isEqualToString:@"血压"]) {
        _chartView.legend.enabled = YES; // 显示图例
        _chartView.legend.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
        _chartView.legend.verticalAlignment = ChartLegendVerticalAlignmentTop;
    }else {
        _chartView.legend.enabled = NO; // 显示图例
    }

    _chartView.doubleTapToZoomEnabled = NO; //是否支持双击缩放
    //高亮点击
    _chartView.highlightPerTapEnabled = YES;
    //没有数据时显示
    _chartView.noDataText = @"没有数据";

    ChartYAxis *leftAxis = _chartView.leftAxis;
    [leftAxis removeAllLimitLines];
    [leftAxis setXOffset:10];  // y轴水平偏移

//    leftAxis.gridLineDashLengths = @[@5.f, @5.f];
    leftAxis.drawZeroLineEnabled = NO;
    leftAxis.drawLimitLinesBehindDataEnabled = YES;
//    leftAxis.drawGridLinesEnabled = NO;//不绘制网格线
    leftAxis.gridColor = CLightGrayColor;
    _chartView.rightAxis.enabled = NO;
    leftAxis.granularityEnabled = YES;
//    leftAxis.labelFont = DYFont(14);


    //[_chartView.viewPortHandler setMaximumScaleY: 2.f];
    //[_chartView.viewPortHandler setMaximumScaleX: 2.f];

//    ChartMarkerImage *marker = [[ChartMarkerImage alloc] init];

    [self setupXAixTitle];

    _chartView.legend.form = ChartLegendFormLine;
    [_chartView animateWithXAxisDuration:2.5];


    ChartXAxis *xAxis = _chartView.xAxis;
//    xAxis.labelFont = DYFont(14);
//    xAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//设置X轴线宽
    xAxis.labelPosition = XAxisLabelPositionBottom;//X轴的显示位置，默认是显示在上面的
    xAxis.drawGridLinesEnabled = NO;//不绘制网格线
//    xAxis.labelCount = 7;// 网格线数量
    xAxis.labelTextColor = KBlackColor;//label文字颜色
    xAxis.granularity = 1;

    [self setData];
}

- (void)setupXAixTitle {

    ChartIndexAxisValueFormatter *format = [[ChartIndexAxisValueFormatter alloc] initWithValues: _xAixTitles];
    [_chartView.xAxis setValueFormatter:format];
  
    BalloonMarker *marker = [[BalloonMarker alloc]
                             initWithColor: CNavBgColor
                             font: DYFont(14)
                             textColor: UIColor.whiteColor
                             insets: UIEdgeInsetsMake(8.0, 8.0, 20.0, 8.0)
                             xAxisValueFormatter: format
                             yPrefix: [NSString stringWithFormat:@"%@：", _model.check_name]];
    marker.chartView = _chartView;
    marker.minimumSize = CGSizeMake(80.f, 40.f);
    _chartView.marker = marker;
}

- (void)setData
{
  
    NSMutableArray *dataSets = [NSMutableArray array];
    
    double leftAxisMin = 0;
    double leftAxisMax = 0;
    NSArray *names = @[@"舒张压", @"收缩压"];

    NSInteger i = 0;
    for (NSArray *values in _yValues) {
        
        NSMutableArray *yVals = [NSMutableArray array];
        for (int i = 0; i < values.count; i++)
        {
            NSString *valStr = [NSString stringWithFormat:@"%@", values[i]];
            double val = [valStr doubleValue];
            leftAxisMax = MAX(val, leftAxisMax);
            leftAxisMin = MIN(val, leftAxisMax);
            ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:val];
            [yVals addObject:entry];
        }
        
        NSString *lineName = @"";
        if ([_model.check_name isEqualToString:@"血压"]) {
            lineName = names[i];
        }else {
            lineName = _model.check_name;
        }

        LineChartDataSet *dataSet = [[LineChartDataSet alloc] initWithEntries:yVals label: lineName];

        dataSet.mode = LineChartModeCubicBezier;
        dataSet.lineWidth = 2.0f;//折线宽度
        [dataSet setColor:_lineColors[i]]; //折线颜色
        dataSet.drawValuesEnabled = NO;//是否在拐点处显示数据
        dataSet.drawFilledEnabled = YES; // 填充色
        dataSet.fillColor = [_lineColors[i] colorWithAlphaComponent:0.4];
        
    //        dataSet.valueColors = @[self.colorArray[i]];//折线拐点处显示数据的颜色
    //        dataSet.drawSteppedEnabled = NO;//是否开启绘制阶梯样式的折线图
        dataSet.drawCirclesEnabled = YES;//是否绘制拐点
        dataSet.circleRadius = 3.0f;//拐点半径
        dataSet.axisDependency = AxisDependencyLeft;
        dataSet.drawCircleHoleEnabled = YES;//是否绘制中间的空心
        dataSet.circleHoleRadius = 2.0f;//空心的半径
        dataSet.circleHoleColor = KWhiteColor;//空心的颜色
        [dataSet setCircleColor:_lineColors[i]];
        dataSet.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
        dataSet.highlightColor = _lineColors[i];
        dataSet.valueFont = [UIFont systemFontOfSize:12];
        
        [dataSets addObject:dataSet];
        i++;
    }
    
//    self.chartView.leftAxis.axisMaximum = leftAxisMax;
//    self.chartView.leftAxis.axisMinimum = leftAxisMin;
    
    LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
    self.chartView.data = nil;
    self.chartView.data = data;
    [self.chartView animateWithXAxisDuration:0.3f];
}


- (void)initUI {
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - ZXNavBarHeight - 47 - ZXSafeAreaBottom) style:UITableViewStyleGrouped];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
    
    [_tableView registerClass:HEHealthCheckRecodCell.class forCellReuseIdentifier: KHEHealthCheckRecodCell];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
    
    __weak __typeof(&*self)weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.isFromHeadRefresh = YES;
        [weakSelf loadData];
    }];
}

- (UIButton *)bottomView {
    if (!_bottomView) {
        UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:bottomView];
        bottomView.backgroundColor = CNavBgColor;
        _bottomView.titleLabel.font = DYBlodFont(18);
        [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
        [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
        
        [bottomView setTitle: [NSString stringWithFormat:@"记录%@", _model.check_name] forState:UIControlStateNormal];
        
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_offset(49);
            make.bottom.offset(-ZXSafeAreaBottom);
        }];
        
        _bottomView = bottomView;
    }
    return _bottomView;
}
  
- (void)submit {
    // 性别
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]init];
    stringPickerView.pickerMode = BRStringPickerComponentMulti;
    stringPickerView.title = _model.check_name;
    stringPickerView.dataSourceArr = [self getPickerData];
    stringPickerView.selectValues = [self getPickerDefualtVal];
    
    KWeakSelf
    stringPickerView.resultModelArrayBlock = ^(NSArray<BRResultModel *> * _Nullable resultModelArr) {
      DLog(@"")
        
        NSString *value = @"";
        if (resultModelArr.count == 1) {
            BRResultModel *model = resultModelArr.firstObject;
            NSArray *strs = [model.value componentsSeparatedByString:weakSelf.model.check_unit];
            value = strs.firstObject;
        }
        else {
            BRResultModel *model1 = resultModelArr[0];
            BRResultModel *model2 = resultModelArr[1];
            BRResultModel *model3 = resultModelArr[2];

            NSArray *strs1 = [model1.value componentsSeparatedByString:weakSelf.model.check_unit];
            NSArray *strs3 = [model3.value componentsSeparatedByString:weakSelf.model.check_unit];

            value = [NSString stringWithFormat:@"%@%@%@", strs1.firstObject, model2.value, strs3.firstObject];
        }
        
        [weakSelf saveCheckValue: value];
    };
    
    // 自定义弹框样式
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:CNavBgColor];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

- (void)saveCheckValue:(NSString *)val {
    
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:val forKey:@"check_value"];
    [params setValue:_model.check_code forKey:@"check_code"];
    [params setValue:_model.check_name forKey:@"check_name"];
    [params setValue:_selectUser.id forKey:@"usid"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KHealthSave parameters:params success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toastBottom:@"操作成功"];
        }
        [self.tableView.mj_header beginRefreshing];
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (NSArray *)getPickerData {
    
    NSInteger min = 0;
    NSInteger max = 0;
    NSMutableArray *data = @[].mutableCopy;
    BOOL isOne = NO;

    if ([@"身高" isEqualToString:_model.check_name]) {
        min = 90;
        max = 250;
        isOne = YES;
    }
    else if ([@"体重" isEqualToString:_model.check_name]) {
        min = 20;
        max = 150;
        isOne = YES;
    }
    else if ([@"睡眠" isEqualToString:_model.check_name]) {
        min = 0;
        max = 24;
        isOne = YES;
    }
    else if ([@"呼吸次数" isEqualToString:_model.check_name]) {
        min = 10;
        max = 60;
        isOne = YES;
    }
    else if ([@"血氧" isEqualToString:_model.check_name]) {
        min = 50;
        max = 150;
        isOne = YES;
    }
    else if ([@"静息心率" isEqualToString:_model.check_name]) {
        min = 30;
        max = 220;
        isOne = YES;
    }
    
    if (isOne) {
        NSMutableArray *vals = @[].mutableCopy;
        for (NSInteger i = min; i <= max; i++) {
            [vals addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }
        [data addObject:vals];
    }
    
    if ([@"体温" isEqualToString:_model.check_name]) {
       min = 34;
       max = 43;
       
       NSMutableArray *vals1 = @[].mutableCopy;
       NSMutableArray *vals2 = @[].mutableCopy;
       NSMutableArray *vals3 = @[].mutableCopy;

       for (NSInteger i = min; i <= max; i++) {
           [vals1 addObject:[NSString stringWithFormat:@"%ld", i]];
       }
       [vals2 addObject:@"."];
       for (NSInteger i = 0; i <= 9; i++) {
           [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
       }

       [data addObject:vals1];
       [data addObject:vals2];
       [data addObject:vals3];
   }
    else if ([@"血压" isEqualToString:_model.check_name]) {
        min = 30;
        max = 150;
        
        NSMutableArray *vals1 = @[].mutableCopy;
        NSMutableArray *vals2 = @[].mutableCopy;
        NSMutableArray *vals3 = @[].mutableCopy;

        for (NSInteger i = min; i <= max; i++) {
            [vals1 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }
        [vals2 addObject:@"/"];
        for (NSInteger i = 50; i <= 250; i++) {
            [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }

        [data addObject:vals1];
        [data addObject:vals2];
        [data addObject:vals3];
    }
    else if ([@"血糖" isEqualToString:_model.check_name]) {
        min = 0;
        max = 25;
        
        NSMutableArray *vals1 = @[].mutableCopy;
        NSMutableArray *vals2 = @[].mutableCopy;
        NSMutableArray *vals3 = @[].mutableCopy;

        for (NSInteger i = min; i <= max; i++) {
            [vals1 addObject:[NSString stringWithFormat:@"%ld", i]];
        }
        [vals2 addObject:@"."];
        for (NSInteger i = 0; i <= 9; i++) {
            [vals3 addObject:[NSString stringWithFormat:@"%ld%@", i, _model.check_unit]];
        }

        [data addObject:vals1];
        [data addObject:vals2];
        [data addObject:vals3];
    }
    return data;
}

- (NSArray *)getPickerDefualtVal {
    if ([@"身高" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"175%@", _model.check_unit]];
    }
    else if ([@"体重" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"65%@", _model.check_unit]];
    }
    else if ([@"体温" isEqualToString:_model.check_name]) {
        return @[@"36", @"." ,[NSString stringWithFormat:@"5%@", _model.check_unit]];
    }
    else if ([@"睡眠" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"8%@", _model.check_unit]];
    }
    else if ([@"血压" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"70%@", _model.check_unit], @"/", [NSString stringWithFormat:@"120%@", _model.check_unit]];
    }
    else if ([@"血糖" isEqualToString:_model.check_name]) {
        return @[@"7", @"." ,[NSString stringWithFormat:@"0%@", _model.check_unit]];
    }
    else if ([@"呼吸次数" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"20%@", _model.check_unit]];
    }
    else if ([@"血氧" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"95%@", _model.check_unit]];
    }
    else if ([@"静息心率" isEqualToString:_model.check_name]) {
        return @[[NSString stringWithFormat:@"60%@", _model.check_unit]];
    }
    return @[];
}
 

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEHealthCheckRecodCell *cell = [tableView dequeueReusableCellWithIdentifier: KHEHealthCheckRecodCell];
    cell.model = _dataSourceArr[indexPath.row];
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 
   return [tableView fd_heightForCellWithIdentifier: KHEHealthCheckRecodCell cacheByIndexPath:indexPath configuration:^(HEHealthCheckRecodCell *cell) {
       cell.model = self.dataSourceArr[indexPath.row];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.dataSourceArr.count > 0) {
        return 50;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
  
    UILabel *_titleLb = [UILabel new];
    _titleLb.text = [NSString stringWithFormat:@"   %@记录",_model.check_name];
    _titleLb.font = DYBlodFont(18);
    _titleLb.backgroundColor = KWhiteColor;
    _titleLb.textColor = CNavLightBlackColor;
    [v addSubview:_titleLb];
    
    [_titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(v).mas_offset(10);
        make.left.equalTo(v).mas_offset(0);
        make.right.equalTo(v).mas_offset(-10);
        make.bottom.equalTo(v).mas_offset(-0);
    }];
    
    return v;
}

@end
